package ue

import (
	"cybertwin/utils/timer"
	"github.com/panjf2000/gnet/v2"
	log "github.com/sirupsen/logrus"
	"sync"
)

// DirectClient 直接连接echo server的客户端
type DirectClient struct {
	gnet.BuiltinEventEngine
	eng               gnet.Engine
	Wg                *sync.WaitGroup
	TimerForReconnect *timer.Timer
}

type DirectClientConnectionContext struct {
	time timer.Timer
}

func NewDirectionConnectionContext() *DirectClientConnectionContext {
	return &DirectClientConnectionContext{
		time: timer.Timer{},
	}
}

func (client *DirectClient) OnBoot(eng gnet.Engine) (action gnet.Action) {
	log.Infoln("[OnBoot]-DirectClient starting")
	client.eng = eng
	return
}

func (client *DirectClient) OnOpen(conn gnet.Conn) (out []byte, action gnet.Action) {
	// 连接开启后，直接发送请求
	context := NewDirectionConnectionContext()
	conn.SetContext(context)
	//conn.Write([]byte("Hello, echo server"))
	return
}

func (client *DirectClient) OnTraffic(conn gnet.Conn) (action gnet.Action) {
	buf, _ := conn.Next(-1)
	dura := client.TimerForReconnect.Stop()
	log.Infof("[DirectClient]-[OnTraffic]-接收到来自echo server的消息:%s，耗时：%s", buf, dura)
	action = gnet.Close
	return
}
